var doListUrl = "/toList.do";
var toListUrl = "/doList.do";
var sect_orgName="",sect_orgCode="",sectName="", tips = "", allFields = "";
/*页面初始化*/
$(document).ready(function () {
    setDioalog($("#sect_dlg"));
    setDioalog($("#info_dialog"));
    setDioalog($("#js_seller_org"));
    setDioalog($("#sec_local_dlg"));
    setDioalog($("#cer_dlg"));
    setDioalog($("#cer_apply_dlg"));
    setDatePicker();
});


function checkValidate() {
    var bValid = true;
    sect_orgName = $("#insert_orgName"),
    sect_orgCode = $("#insert_orgCode"),
    sectName = $("#insert_name");
    tips = $("#validate_tips");
    allFields = $([]).add(sect_orgName).add(sect_orgCode).add(sectName);

    allFields.removeClass("ui-state-error");

    bValid = bValid && checkLength(sect_orgName, "机构名称", 1,10);
    bValid = bValid && checkLength(sect_orgCode, "组织机构代码", 1,45);
    bValid = bValid && checkLength(sectName, "码段", 4,4);

    bValid = bValid && checkRegexp(sectName, new RegExp("^[A-Fa-f0-9]{" +4+ "," +4+ "}$"), "请输入6位，范围为：A~F、a~f英文字母、0~9数字");

    return bValid;
}
/*validate校验end*/

/*日期空间加载*/
function setDatePicker() {
    $("#insert_date").datepicker({
        showOn: "both",
        buttonImage: "../images/date_select.png",
        buttonText: "日期选择",
        buttonImageOnly: true,
        dateFormat: "yy-mm-dd",
        changeMonth: true,
        changeYear:true
    });
}

/*搜索*/
function sect_search(url) {
    var jsonStr = {
        flg:1,
        orgName:$('#js_name').val(),
        orgCode:$('#js_code').val(),
        name:$('#js_sn_code').val(),
        page:""
    };
    doList(jsonStr,url+doListUrl, $("#sect_table"));
};

/*展示弹窗公用*/
function sectShowDialog(type,title,url){
    $("#sect_dlg").dialog({
        dialogClass: "my-dialog",
        autoOpen: true,
        width: 850,
        modal: true,
        title:title,
        buttons: {
            保存: function () {
                if(checkValidate()){
                    storeForm(url, false)
                }
            },
            取消: function () {
                if(tips!="" || allFields!=""){
                    tips.text("").removeClass("ui-state-highlight");
                    allFields.removeClass( "ui-state-error").val("");
                }
                $(this).dialog('destroy');
                $(this).dialog("close");
            }
        },
        close: function() {
            tips.text("").removeClass("ui-state-highlight");
            allFields.removeClass( "ui-state-error").val("");
        },
        open:function(){
        }
    });
}
/*跳到新增码段页面*/
function create(url) {
    var createUrl = url + "/create.do";
    sectShowDialog(1,"新增码段",createUrl);
    $(':input', '#sect_fm')
        .not(':button, :submit, :reset, :hidden')
        .val('')
        .removeAttr('checked')
        .removeAttr('selected');
    $('#sellect_org_btn').removeAttr("disabled");
    $('#insert_name').removeAttr("readonly");
};

/*码段延期处理*/
function deferred(url, id) {
    var modifyUrl = url + "/modify.do?id=" +id;
    $.post(url + "/findId.do?id=" + id, function (result) {
        $("#sect_dlg").html(result);
        $('#sellect_org_btn').attr({"disabled": "disabled"});
        $('#insert_name').attr({"readonly": "readonly"});
        setDatePicker();
    });
    sectShowDialog(2,"码段延期",modifyUrl);
}

/**
 * 码段状态操作
 * @param id、state：码段id、码段状态
 */
function modifyState(url, id, state) {
    var srt = "停用";
    var st = 2;
    if (state == 2) {
        srt = "启用"
        st = 1;
    }
    if (id != null) {
        $("#info_msg").text("您确定要" + srt + "吗？");
        $("#info_dialog").dialog({
            dialogClass: "my-dialog",
            autoOpen: true,
            modal: true,
            title: srt + '操作',
            buttons: {
                确定: function () {
                    var to_url='/modifyState.do?id=' + id + "&state=" + parseInt(st);
                    storeForm(url+to_url, false);
                },
                取消: function () {
                    $(this).dialog("close");
                }
            }
        });
    }
};

/*选择机构*/
function choseOrg(url) {
    $("#js_seller_org").dialog({
        dialogClass: "my-dialog",
        autoOpen: true,
        width: 900,
        modal: true,
        title: "选择机构",
        buttons: {
            取消: function () {
                $(this).dialog("close");
            }
        },
        open: function () {
            var jsonStr = {
                flg:2,
                name:"",
                orgCode:"",
                orgId:"",
                page:""
            }
            doList(jsonStr,url+toListUrl, $("#js_seller_org"));
        }
    });
}

/**
 * 保存表单数据
 * @param url
 * @param isLocal
 */
function storeForm(url, isLocal) {
    var sec = $('#sect_fm').serialize();
    if (isLocal)
        sec = $('#data_local_fm').serialize();
    $.ajax({
        cache: true,
        type: "POST",
        url: url,
        data: sec,
        async: false,
        error: function (request) {
            alert("Connection error");
        },
        success: function (result) {
            var data = $.parseJSON(result);
            if (data.ok) {
                $("#sect_dlg").dialog("close");
                $("#sec_local_dlg").dialog("close");
                window.location.reload(false);
            }else{
                $("#info_msg").text(data.msg);
                $("#info_dialog").dialog({
                    dialogClass: "my-dialog",
                    autoOpen: true,
                    modal: true,
                    title: '提示信息',
                    buttons: {
                        确定: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            }
        }
    });
}

/*删除操作*/
function delSect(url, ids) {
    if (ids != null) {
        $("#info_msg").text("您确定要删除选择的码段吗？删除后无法恢复！");
        $("#info_dialog").dialog({
            dialogClass: "my-dialog",
            autoOpen: true,
            modal: true,
            title: '删除操作',
            buttons: {
                确定: function () {
                    $.post(url + '/delete.do?ids=' + ids, function (result) {
                        if (result.ok) {
                            $("#info_dialog").dialog("close");
                            window.location.reload(false);
                        }
                        else {
                            alert(result.msg);
                        }
                    }, 'json');
                },
                取消: function () {
                    $(this).dialog("close");
                }
            }
        });
    }
}

/**
 * 修改码段信息（局部修改）
 * @param sid
 * Added By Zmt
 */
function localModify(sid){
    $.post("/cer/fetchSection.do?id=" + sid, function (result) {
        $("#sec_local_dlg").html(result);
    });
    $("#sec_local_dlg").dialog({
        dialogClass: "my-dialog",
        autoOpen: true,
        width: 850,
        modal: true,
        title: "编辑证书",
        buttons: {
            保存: function () {
                storeForm("/cer/modifyLocalSection.do?sid=" + sid, true)
            },
            取消: function () {
                $(this).dialog("close");
            }
        }
    });
}